<?php
/** Copyright 2014 TinPhp Systems, Inc.
 * @author zhangxilian 2013-8-15
 */
if (!defined('IN_TINPHP')) {
    exit('Access Denied');
}

require_once(TIN_APP_PATH . 'include/TinAppController.php');
require_once (TIN_APP_PATH . 'include/Auth.php');

class AjaxUploadController extends TinAppController {
    
	private $user;
	
    public function __construct() {
        parent::__construct();
        $this->setPageHeader();
        T::$tplFile = "public/empty";        
        $this->user = Auth::getUserInfo();        
        if(!$this->user || $this->user==null){
        	$result = array();
        	$result["code"] = "error";
        	$result["msg"] = "您还没有登录或登录超时";
        	echo $this->getResources($result);
        	exit();
        }
    }
    
    /** 上传用户头像
     * @author ZhangXiLian 2014-9-02*/
    public function actionUploadUserHeader(){
    	$result = array();
		$result["code"] = "error";
		$result["msg"] = "请选择要上传的文件";
		if ($_FILES["image_file"]["tmp_name"][0]) {
			$image = $_FILES["image_file"];
			$file_type = array ('gif', 'jpg', 'jpeg', 'pjpeg', 'png');
			$result = $this->uploadServer($image, $file_type, 200000);				
		}
		echo $this->getResources($result);
    }
	/**
	 * 上传图片，压缩
	 * @author ZhangXiLian 2014.06.13
	 * */
	public function actionUploadImg() {
		$result = array();
		$result["code"] = "error";
		$result["msg"] = "请选择要上传的文件";		
		if ($_FILES["image_file"]["tmp_name"][0]) {
			$image = $_FILES["image_file"];
			$file_type = array ('gif', 'jpg', 'jpeg', 'pjpeg','bmp', 'x-png', 'png');
			$result = $this->uploadServer($image, $file_type, 1024000, 2, 360);
			//echo $result;
		}
		echo $this->getResources($result);
	}
	/**
	 * 上传图片(主用于编辑器)
	 * @author ZhangXiLian 2014.09.13
	 * */
	public function actionUploadEdit() {
// 		$result = array();
// 		$result["code"] = "error";
// 		$result["msg"] = "请选择要上传的文件";
		
// 		$upfile = @ $_FILES['filedata'];
// 		if (isset($upfile)) {
// 			$image = $_FILES["filedata"];
// 			$file_type = array ('gif', 'jpg', 'jpeg', 'pjpeg','bmp', 'x-png', 'png');
// 			$result = $this->uploadServer($image, $file_type, 1024000, 2, 360);
// 		}
// 		echo "{'err':'".$result["msg"]."','msg':'".$result["data"]["name"]."'}";
		//echo $this->getResources($result);
		
		$inputName = 'filedata'; //表单文件域name
		$attachDir = TIN_UPLOAD_SAVE_PATH; //上传文件保存路径，结尾不要带/
		$dirType = 4; //1:按天存入目录 2:按月存入目录 3:按扩展名存目录  建议使用按天存 4 无目录
		$maxAttachSize = 2097152; //最大上传大小，默认是2M
		$upExt = 'txt,rar,zip,jpg,jpeg,gif,png,JPG,JPEG,GIF,PNG,swf,wmv,avi,wma,mp3,mid'; //上传扩展名
		// $msgType=2;//返回上传参数的格式：1，只返回url，2，返回参数数组
		$immediate = isset ($_GET['immediate']) ? $_GET['immediate'] : 0; //立即上传模式，仅为演示用
		//ini_set('date.timezone','Asia/Shanghai');//时区
		
		$err = "";
		$msg = "''";
		$tempPath = $attachDir . date("YmdHis") . mt_rand(10000, 99999) . '.tmp';
		$localName = '';
		
		if (isset ($_SERVER['HTTP_CONTENT_DISPOSITION']) && preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i', $_SERVER['HTTP_CONTENT_DISPOSITION'], $info)) { //HTML5上传
			file_put_contents($tempPath, file_get_contents("php://input"));
			$localName = urldecode($info[2]);			
		} else { //标准表单式上传
			$upfile = @ $_FILES[$inputName];			
			if (!isset ($upfile)) {
				$err = '文件域的name错误';
			} else
				if (!empty ($upfile['error'])) {
					switch ($upfile['error']) {
						case '1' :
							$err = '文件大小超过了php.ini定义的upload_max_filesize值';
							break;
						case '2' :
							$err = '文件大小超过了HTML定义的MAX_FILE_SIZE值';
							break;
						case '3' :
							$err = '文件上传不完全';
							break;
						case '4' :
							$err = '无文件上传';
							break;
						case '6' :
							$err = '缺少临时文件夹';
							break;
						case '7' :
							$err = '写文件失败';
							break;
						case '8' :
							$err = '上传被其它扩展中断';
							break;
						case '999' :
						default :
							$err = '无有效错误代码';
					}
				} else
					if (empty ($upfile['tmp_name']) || $upfile['tmp_name'] == 'none') {
						$err = '无文件上传';
					} else {
						move_uploaded_file($upfile['tmp_name'], $tempPath);
						$localName = $upfile['name'];
					}
		}
		
		if ($err == '') {			
			$fileInfo = pathinfo($localName);
			$extension = $fileInfo['extension'];
			if (preg_match('/' . str_replace(',', '|', $upExt) . '/i', $extension)) {
				$bytes = filesize($tempPath);				
				if ($bytes > $maxAttachSize) {
					$err = '请不要上传大小超过' . $this->formatBytes($maxAttachSize) . '的文件';
				} else {
								switch($dirType)
								{
									case 1: $attachSubDir = 'day_'.date('ymd'); break;
									case 2: $attachSubDir = 'month_'.date('ym'); break;
									case 3: $attachSubDir = 'ext_'.$extension; break;
							        case 4: $attachSubDir = ''; break;
								}
								$attachDir = $attachDir.$attachSubDir;
								if(!is_dir($attachDir))
								{
									@mkdir($attachDir, 0777);
									@fclose(fopen($attachDir.'/index.htm', 'w'));
								}
								PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
								$newFilename=date("YmdHis").mt_rand(1000,9999).'.'.$extension;
								if($dirType == 4){
									$targetPath = $attachDir. $newFilename;
								}else{
									$targetPath = $attachDir.'/'.$newFilename;
								}
		
						rename($tempPath,$targetPath);
								@chmod($targetPath,0755);
								$targetPath=$targetPath;
								if($immediate=='1')$targetPath='!'.$targetPath;
					
					$file = TIN_APP_PATH.$targetPath;
					$url = TIN_UPLOAD_HOST;
					$ch = curl_init($url);
					curl_setopt($ch, CURLOPT_HEADER, 0);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
					curl_setopt($ch, CURLOPT_PROXY, TIN_UPLOAD_PROXY);
					curl_setopt($ch, CURLOPT_POST, 1);
					$array = array (
							'sign' => TIN_UPLOAD_SIGN,
							'type' =>1,	//2压缩
							'file' => '@' . $file
					);
					curl_setopt($ch, CURLOPT_POSTFIELDS, $array);
					$data = curl_exec($ch);
					curl_close($ch);
					unlink($file);
					$result = json_decode($data, true);
					if($result["result"] == "success"){	//适应本系统json规范
						$image_url = $result["name"];
						$msg =  TIN_MEDIA_URL . $image_url;
						
						//--插入数据库--
						$imageData["user_id"] = $this->user['ID'];						
						$imageData["url"] = $msg;
						$imageData["size"] = $bytes;
						$imageId = $this->Logic("ThumbLogic")->insertThumb($imageData);
						//---------------						
					}else{
						$result["msg"] = "链接资源服务器失败。";
					}
		
				}
			} else
				$err = '上传文件扩展名必需为：' . $upExt;
		
			@ unlink($tempPath);
		}
		echo '{"err":"' . $err . '","msg":"' . $msg . '"}';
	}
	
	/** 上传压缩包 */
	public function actionUploadRAR() {
		$result = array();
		$result["code"] = "error";
		$result["msg"] = "请选择要上传的文件";
		if ($_FILES["image_file"]["tmp_name"][0]) {
			$image = $_FILES["image_file"];
			$file_type = array ('rar','zip');			
			$result = $this->uploadServer($image, $file_type, 2048000);				
		}
		echo $this->getResources($result);
	}
	/**
	 * 开始提交服务器验证，并保存上传文件
	 * @param object $image 要上传的文件
	 * @param array $file_type 限制上传文件的格式
	 * @param int $maxSize 限制上传文件的大小
	 * @param int $type 上传方式，默认1:普通上传,2:压缩缩略图配合$width使用
	 * @param int $width 上传图片压缩尺寸，$type=2时有效
	 * @param bool $insertDB 是否需要插入数据库记录
	 * */
	private function uploadServer($image, $file_type, $maxSize, $type=1, $width=320, $insertDB=true){
		$result = array();
		if (!isset ($image)) {
			$result["code"] = "error";
			$result["msg"] = "文件域的name错误";
			return $result;
		}
		$ext = end(explode('/', $image["type"][0]));
		if (!in_array(strtolower($ext), $file_type)) {			
			$result["code"] = "error";
			$result["msg"] = "上传格式不正确";
			return $result;
		}
		if ($image["size"][0] > $maxSize) {
			$result["code"] = "error";
			$result["msg"] = "上传文件大小超过限制";
			return $result;
		}
		
		$path = TIN_APP_PATH . TIN_UPLOAD_SAVE_PATH;
		$res = move_uploaded_file($image['tmp_name'][0], iconv("UTF-8", "gb2312", $path . $image['name'][0]));
		if(TIN_USE_MEDIA_SERVER){
			$file = iconv("UTF-8", "gb2312", $path . $image['name'][0]);
			$url = TIN_UPLOAD_HOST;
			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			// localhost:8888是fiddler的代理，设置此选项用于让fiddler抓获post的请求
			curl_setopt($ch, CURLOPT_PROXY, TIN_UPLOAD_PROXY);
			//下面这一句必须注释，不然Fiddler抓不到Post的http请求
			//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
			curl_setopt($ch, CURLOPT_POST, 1);
			$array = array (
					'sign' => TIN_UPLOAD_SIGN,
					'type' =>$type,	//2压缩
					'width' =>$width,
					//'height' =>360,
					'quantity' => 0.9,
					'file' => '@' . $file
			);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $array);
			$data = curl_exec($ch);
			curl_close($ch);
			unlink($file);
			$result = json_decode($data, true);
			if($result["result"] == "success"){	//适应本系统json规范				
				$result["code"] = "success";
				$result["data"]["name"] = $result["name"];
				unset($result["result"],$result["name"]);
			}else{
				$result["msg"] = "链接资源服务器失败。";
			}
		}else{
			$result["code"] = "success";
			$result["data"]["name"] = TIN_UPLOAD_SAVE_PATH . $image['name'][0];
		}
		//插入数据库
		if($result["code"] == "success" && $insertDB){
			//--插入数据库--
			$imageData["user_id"] = $this->user['ID'];
			if(RequestUtil::getReq("good_id")) $imageData["good_id"] = RequestUtil::getReq("good_id");
			if(RequestUtil::getReq("pro_id")) $imageData["pro_id"] = RequestUtil::getReq("pro_id");
			$imageData["url"] = $result['data']["name"];
			$imageData["size"] = $image['size'][0];
			$imageId = $this->Logic("ThumbLogic")->insertThumb($imageData);
			//---------------
			if ($imageId) {
				$result["data"]["dbid"] = $imageId;
			}
		}
			
		return $result;
	}
}
?>
